package com.jhgsys.internal.sypq.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.jhgsys.internal.common.annotation.Log;
import com.jhgsys.internal.common.controller.BaseController;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.entity.FebsResponse;
import com.jhgsys.internal.common.entity.QueryRequest;
import com.jhgsys.internal.common.entity.FebsConstant;
import com.jhgsys.internal.common.exception.FebsException;
import com.jhgsys.internal.common.utils.DateUtil;
import com.jhgsys.internal.common.utils.FebsUtil;
import com.jhgsys.internal.sypq.entity.ModelShip;
import com.jhgsys.internal.sypq.entity.ModelShipProcess;
import com.jhgsys.internal.sypq.params.OutFinishParams;
import com.jhgsys.internal.sypq.params.ShipModelProcParams;
import com.jhgsys.internal.sypq.service.IModelShipService;
import com.jhgsys.internal.sypq.vo.ModelShipProcsVO;
import com.wuwenze.poi.ExcelKit;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotBlank;
import java.util.Date;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * 船模 Controller
 *
 * @author ganjun
 * @date 2024-11-13 19:03:49
 */
@Slf4j
@Validated
@Controller
public class ModelShipController extends BaseController {

    @Autowired
    private IModelShipService modelShipService;

    @GetMapping(FebsConstant.VIEW_PREFIX + "modelShip")
    @RequiresPermissions("modelShip:view")
    public ModelAndView modelShipIndex(@RequestParam(name="projectName", required=false, defaultValue="") String projectName) {
        String viewPath = jumpPage("sypq/modelShip/modelShipList");
        ModelAndView modelAndView = new ModelAndView(viewPath);
        modelAndView.addObject("projectName", projectName);
        return modelAndView;
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "modelShip/add")
    @RequiresPermissions("modelShip:add")
    public String modelShipAdd(Model model){
        //船模编号
        String dateStr = DateUtil.getDateFormat(new Date(), "yyyyMM");
        Random random = new Random();
        int randomNumber = random.nextInt(10000); // 生成0到9999之间的随机数
        String bmNo = "BM" + dateStr + String.format("%04d", randomNumber); // 格式化为四位数字
        //当前时间
        String now =  DateUtil.getDateFormat(new Date(), "yyyy-MM-dd HH:mm");
        model.addAttribute("bmNo", bmNo);
        model.addAttribute("now", now);
        //项目列表
        model.addAttribute("projList", modelShipService.getProjectList());
        //船模实体
        ModelShip modelShip = new ModelShip();
        model.addAttribute("modelShip", modelShip);
        return jumpPage("sypq/modelShip/modelShipEdit");
    }

    @GetMapping(FebsConstant.VIEW_PREFIX + "modelShip/update/{id}")
    @RequiresPermissions("modelShip:edit")
    public String modelShipUpdate(Model model, @PathVariable("id") String id){
        model.addAttribute("modelShip", modelShipService.findModelShipById(id));
        //项目列表
        model.addAttribute("projList", modelShipService.getProjectList());
        return jumpPage("sypq/modelShip/modelShipEdit");
    }

    /**
     * 查看详情
     * @param model
     * @param id
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "modelShip/view/{id}")
    @RequiresPermissions("modelShip:view")
    public String modelShipView(Model model, @PathVariable("id") String id){
        model.addAttribute("modelShip", modelShipService.findModelShipById(id));
        return jumpPage("sypq/modelShip/modelShipView");
    }

    /**
     * 加工流程页
     * @param model
     * @param id
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "modelShip/process/{id}")
    @RequiresPermissions("modelShip:process")
    public String process(Model model, @PathVariable("id") String id){
        //当前登录人角色（是项目经理返回1，是操作员返回2，两者都是或者是系统管理员返回3）
        model.addAttribute("isPmRole", isPmRole());
        //船模信息
        model.addAttribute("modelShip", modelShipService.findModelShipById(id));
        //加工流程信息
        List<ModelShipProcess> procs = modelShipService.getModelShipProcsByShipId(id);
        model.addAttribute("procs", procs);
        //附件信息
        model.addAttribute("attachs", modelShipService.getModelShipAttachsByShipId(id));
        //检验信息
        model.addAttribute("test", modelShipService.getModelShipTestByShipId(id));
        //获取检验员集合
        model.addAttribute("operateUsers", getUsersByRoleId("533f1044ed1db628316a3e7c35305fd8", "0"));
        //各个步骤完成时间和操作人员
        if(CollectionUtil.isNotEmpty(procs)){
            Map<Integer, ModelShipProcess> procsMap = procs.stream().collect(Collectors.toMap(ModelShipProcess::getProcessStatus, proc ->proc));
            //上传图纸
            ModelShipProcess proc2 = procsMap.get(2);
            model.addAttribute("uploadChartTime", proc2 == null ? "" : proc2.getEndDate() == null ? "" : DateUtil.getDateFormat(proc2.getEndDate(), "yyyy-MM-dd HH:mm"));
            //下料
            ModelShipProcess proc3 = procsMap.get(3);
            model.addAttribute("cutTime", proc3 == null ? "" : proc3.getEndDate() == null ? "" : DateUtil.getDateFormat(proc3.getEndDate(), "yyyy-MM-dd HH:mm"));
            model.addAttribute("cutOperator", proc3 == null ? "" : proc3.getOperator() == null ? "" : proc3.getOperator());
            //粗切
            ModelShipProcess proc4 = procsMap.get(4);
            model.addAttribute("roughCutTime", proc4 == null ? "" : proc4.getEndDate() == null ? "" : DateUtil.getDateFormat(proc4.getEndDate(), "yyyy-MM-dd HH:mm"));
            model.addAttribute("roughCutOperator", proc4 == null ? "" : proc4.getOperator() == null ? "" : proc4.getOperator());
            //精切
            ModelShipProcess proc5 = procsMap.get(5);
            model.addAttribute("fineCutTime", proc5 == null ? "" : proc5.getEndDate() == null ? "" : DateUtil.getDateFormat(proc5.getEndDate(), "yyyy-MM-dd HH:mm"));
            model.addAttribute("fineCutOperator", proc5 == null ? "" : proc5.getOperator() == null ? "" : proc5.getOperator());
            //修模
            ModelShipProcess proc6 = procsMap.get(6);
            model.addAttribute("modRepairTime", proc6 == null ? "" : proc6.getEndDate() == null ? "" : DateUtil.getDateFormat(proc6.getEndDate(), "yyyy-MM-dd HH:mm"));
            model.addAttribute("modRepairOperator", proc6 == null ? "" : proc6.getOperator() == null ? "" : proc6.getOperator());
            //油漆
            ModelShipProcess proc7 = procsMap.get(7);
            model.addAttribute("paintTime", proc7 == null ? "" : proc7.getEndDate() == null ? "" : DateUtil.getDateFormat(proc7.getEndDate(), "yyyy-MM-dd HH:mm"));
            model.addAttribute("paintOperator", proc7 == null ? "" : proc7.getOperator() == null ? "" : proc7.getOperator());
        }
        return jumpPage("sypq/modelShip/modelShipProcess");
    }

    /**
     * 操作记录页面
     * @param model
     * @param id
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "modelShip/toProcsPage/{id}")
    public String toProcsPage(Model model, @PathVariable("id") String id){
        model.addAttribute("id", id);
        return jumpPage("sypq/modelShip/procList");
    }

    @GetMapping("modelShip/getProcList/{id}")
    @ResponseBody
    public FebsResponse getProcList(@PathVariable("id") String id){
        //加工流程信息
        List<ModelShipProcsVO> procs = modelShipService.getModelShipProcsVOByShipId(id);
        return success(procs);
    }

    /**
     * 外带-完成
     * @param model
     * @param id
     * @return
     */
    @GetMapping(FebsConstant.VIEW_PREFIX + "modelShip/outFinish/{id}")
    @RequiresPermissions("modelShip:outFinish")
    public String outFinish(Model model, @PathVariable("id") String id){
        model.addAttribute("modelShip", modelShipService.findModelShipById(id));
        return jumpPage("sypq/modelShip/modelShipOutFinish");
    }


    /**
     * 查询（所有）
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @GetMapping("modelShip")
    @ResponseBody
    @RequiresPermissions("modelShip:view")
    public FebsResponse getAllModelShips(ModelShip modelShip) {
        try {
            return success(modelShipService.findModelShipList(modelShip));
        }catch (Exception ex){
            return failure(ex);
        }

    }

    /**
     * 查询（分页）
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @GetMapping("modelShip/list")
    @ResponseBody
    @RequiresPermissions("modelShip:view")
    public FebsResponse modelShipList(QueryRequest request, @Param("demondFinishTime") String demondFinishTime, @Param("name") String name, @Param("statusSearch") String statusSearch, @Param("shipCodeSearch") String shipCodeSearch) {
        try {
            Map<String, Object> dataTable = getDataTable(this.modelShipService.findModelShipPage(request, demondFinishTime, name, statusSearch, shipCodeSearch));
            return success(dataTable);
        }catch (Exception ex){
            return failure(ex);
        }
    }

    /**
     * 导出
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @GetMapping("modelShip/export")
    @ResponseBody
    @RequiresPermissions("modelShip:view")
    public void export(QueryRequest request, @Param("demondFinishTime") String demondFinishTime, @Param("name") String name, @Param("statusSearch") String statusSearch, @Param("shipCodeSearch") String shipCodeSearch, HttpServletResponse response) throws FebsException {
        try {
            List<ModelShip> list  = modelShipService.export(request, demondFinishTime, name,statusSearch, shipCodeSearch);
            ExcelKit.$Export(ModelShip.class, response).downXlsx(list, false);
        }catch (Exception ex){
            String message = "导出Excel失败";
            log.error(message, ex);
            throw new FebsException(message);
        }
    }

    /**
     * 新增 ModelShip
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @Log("新增ModelShip")
    @PostMapping("modelShip")
    @ResponseBody
    @RequiresPermissions("modelShip:add")
    public FebsResponse addModelShip(@Valid @RequestBody ModelShip modelShip) throws FebsException {
        try {
            this.modelShipService.createModelShip(modelShip);
            return success();
        } catch (Exception ex) {
            return failure(ex,"新增失败");
        }
    }

    /**
     * 逻辑删除 ModelShip
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @Log("逻辑删除ModelShip")
    @GetMapping("modelShip/delete/{id}")
    @ResponseBody
    @RequiresPermissions("modelShip:delete")
    public FebsResponse deleteModelShip(@PathVariable("id") String modelShipIds) throws FebsException {
        try {
            ModelShip modelShip = new ModelShip();
            modelShip.setDeletedBy(getCurrentUser().getUserName());
            modelShip.setDeletedTime(new Date());
            modelShip.setDeletedFlg(FebsConstant.INVALID);
            this.modelShipService.deleteModelShip(modelShip,modelShipIds);
            return success();
        } catch (Exception ex) {
            return failure(ex,"删除失败");
        }
    }

    /**
    * 物理删除 ModelShip
    * @author ganjun
    * @date 2024-11-13 19:03:49
    */
    @Log("物理删除ModelShip")
    @GetMapping("modelShip/physicallyDelete/{id}")
    @ResponseBody
    @RequiresPermissions("modelShip:delete")
    public FebsResponse physicallyDeleteModelShip(@PathVariable("id") String modelShipIds) throws FebsException {
        try {
            this.modelShipService.physicallyDeleteModelShip(modelShipIds);
            return success();
        } catch (Exception ex) {
            return failure(ex,"删除失败");
        }
    }

    /**
     * 修改 ModelShip
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @Log("修改ModelShip")
    @PostMapping("modelShip/update")
    @ResponseBody
    @RequiresPermissions("modelShip:edit")
    public FebsResponse updateModelShip(@RequestBody ModelShip modelShip) throws FebsException {
        try {
            this.modelShipService.updateModelShip(modelShip);
            return success();
        } catch (Exception ex) {
            return failure(ex,"修改失败");
        }
    }

    /**
     * 外带 ModelShip完成
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @Log("外带ModelShip完成")
    @PostMapping("modelShip/outFinish")
    @ResponseBody
    @RequiresPermissions("modelShip:outFinish")
    public FebsResponse outFinish(@RequestBody OutFinishParams params) throws FebsException {
        try {
            this.modelShipService.outFinish(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 加工流程-开始
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @Log("修改ModelShip")
    @PostMapping("modelShip/startProc")
    @ResponseBody
    @RequiresPermissions("modelShip:process")
    public FebsResponse startProc(@RequestBody ShipModelProcParams params) throws FebsException {
        try {
            params.setOperator(getCurrentUser().getUserId());
            modelShipService.startProc(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 上传文件
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @Log("modelShip上传图纸")
    @PostMapping("modelShip/uploadChart")
    @ResponseBody
    @RequiresPermissions("modelShip:process")
    public FebsResponse uploadChart(@RequestBody ShipModelProcParams params){
        try {
            params.setOperator(getCurrentUser().getUserId());
            modelShipService.uploadChart(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }

    }

    /**
     * 下料
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @Log("modelShip下料")
    @PostMapping("modelShip/cutting")
    @ResponseBody
    @RequiresPermissions("modelShip:process")
    public FebsResponse cutting(@RequestBody ShipModelProcParams params){
        try {
//            params.setOperator(getCurrentUser().getUserName());
            modelShipService.cutting(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 粗切
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @Log("modelShip粗切")
    @PostMapping("modelShip/roughCut")
    @ResponseBody
    @RequiresPermissions("modelShip:process")
    public FebsResponse roughCut(@RequestBody ShipModelProcParams params){
        try {
//            params.setOperator(getCurrentUser().getUserName());
            modelShipService.routhCut(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 精切
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @Log("modelShip精切")
    @PostMapping("modelShip/fineCut")
    @ResponseBody
    @RequiresPermissions("modelShip:process")
    public FebsResponse fineCut(@RequestBody ShipModelProcParams params){
        try {
//            params.setOperator(getCurrentUser().getUserName());
            modelShipService.fineCut(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 修模
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @Log("modelShip修模")
    @PostMapping("modelShip/modRepair")
    @ResponseBody
    @RequiresPermissions("modelShip:process")
    public FebsResponse modRepair(@RequestBody ShipModelProcParams params){
        try {
//            params.setOperator(getCurrentUser().getUserName());
            modelShipService.modRepair(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 油漆
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @Log("modelShip油漆")
    @PostMapping("modelShip/paint")
    @ResponseBody
    @RequiresPermissions("modelShip:process")
    public FebsResponse paint(@RequestBody ShipModelProcParams params){
        try {
//            params.setOperator(getCurrentUser().getUserId());
            modelShipService.paint(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 完成
     * @author ganjun
     * @date 2024-11-17 19:03:49
     */
    @Log("modelShip完成")
    @PostMapping("modelShip/finish")
    @ResponseBody
    @RequiresPermissions("modelShip:process")
    public FebsResponse finish(@RequestBody ShipModelProcParams params){
        try {
            params.setOperator(getCurrentUser().getUserId());
            modelShipService.finish(params);
            return success();
        } catch (Exception ex) {
            return failure(ex,"提交失败");
        }
    }

    /**
     * 生成船模加工申请表
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @GetMapping("modelShip/expApplyForm")
    @ResponseBody
    @RequiresPermissions("modelShip:view")
    public void expApplyForm(String id, HttpServletResponse response) throws FebsException {
        try {
            modelShipService.expApplyForm(id, response);
        }catch (Exception ex){
            String message = "导出生成船模加工申请表失败";
            log.error(message, ex);
            throw new FebsException(message);
        }
    }

    /**
     * 生成船模质量检验表
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @GetMapping("modelShip/expCheckForm")
    @ResponseBody
    @RequiresPermissions("modelShip:view")
    public void expCheckForm(String id, HttpServletResponse response) throws FebsException {
        try {
            modelShipService.expShipModelCheckForm(id, response);
        }catch (Exception ex){
            String message = "导出船模质量检验表失败";
            log.error(message, ex);
            throw new FebsException(message);
        }
    }


    /**
     * 生成船模加工进度及检验表
     * @author ganjun
     * @date 2024-11-13 19:03:49
     */
    @GetMapping("modelShip/expProcForm")
    @ResponseBody
    @RequiresPermissions("modelShip:view")
    public void expProcForm(String id, HttpServletResponse response) throws FebsException {
        try {
            modelShipService.expProcForm(id, response);
        }catch (Exception ex){
            String message = "导出船模加工进度及检验表失败";
            log.error(message, ex);
            throw new FebsException(message);
        }
    }

}
